package se.webbzon.boltzmann.game.event;

import se.webbzon.boltzmann.game.object.player.AbstractPlayerCharacter;
import se.webbzon.boltzmann.game.sequence.Sequence;
import se.webbzon.boltzmann.game.sequence.Sequences;
import se.webbzon.boltzmann.game.sequence.builder.AbstractSequenceBinding;
import se.webbzon.boltzmann.inventory.Inventory;
import se.webbzon.boltzmann.item.AbstractItem;
import se.webbzon.boltzmann.item.ItemGroup;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldobject.WorldObject;

public class StoreItemEvent extends AbstractGameEvent {
	
	// The sequence associated with this game event
	private final Sequence sequence;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Stores the item at index argument[0] for the current player
	 * in the variable with the name argument[1]. **/
	public StoreItemEvent(String[] arguments, Sequence sequence) {
		super(arguments);
		this.sequence = sequence;
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override protected void onBegin(WorldArea world) {
		if (arguments() >= 2) {
			final int index = (int) 
					((double) Sequences.parse(sequence, getArgument(0)));
			
			// Retrieve the inventory of the player and the
			// player environment
			final WorldObject wso = 
					sequence.getBinding(AbstractSequenceBinding.PLAYER);
			final Inventory inv = 
					((AbstractPlayerCharacter) wso).getPlayer().getInventory();
			
			final int row = index / inv.getColumns();
			final int column = index % inv.getColumns();
			AbstractItem item = inv.getItem(row, column);
			if (item != null)
				Sequences.set(sequence, getArgument(1), (double) ItemGroup.instance().getId(item));
			else
				exception(	"No item in inventory at position (" + 
							row +  "," + column + ").");
		} else
			exception("Argument exception.");
		end();
	}

	@Override protected void onEnd() {};

}
